package com.google.code.mamule.integration;

import com.google.code.mamule.config.MamuleSecurity;
import com.google.code.mamule.user.User;
import com.google.code.mamule.user.UserRepository;
import com.google.common.collect.ImmutableList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA. User: borck_000 ; Date: 12/23/13 ; Time: 4:02 PM
 */
@Service("userDetailsService")
public class MamuleUserDetailsService implements UserDetailsService {

  private static final Logger log = LoggerFactory.getLogger(MamuleUserDetailsService.class);

  // KEEP THIS SECRET (:
  private static final String ADMIN_NAME = "admin";
  private static final String ADMIN_PASS = "root";

  @Autowired
  private UserRepository users;

  @Override
  public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    log.info("authenticating : {}", username);
    // intercept admin login
    if (ADMIN_NAME.equals(username)) {
      log.info("admin login");
      return new org.springframework.security.core.userdetails.User(ADMIN_NAME, ADMIN_PASS,
                                                                    ImmutableList.of(
                                                                        MamuleSecurity.ROLE_ADMIN));
    }
    User active = users.findOne(username);
    log.info("fetched user details {}", active);
    if (active == null) {
      throw new UsernameNotFoundException(username);
    } else {
      return new org.springframework.security.core.userdetails.User(active.getUsername(),
                                                                    active.getPassword(),
                                                                    ImmutableList.of(
                                                                        MamuleSecurity.ROLE_USER));
    }
  }
}
